//
//  StoneStreetStoreDetailViewController.m
//  Globalstone
//
//  Created by 刘建峰 on 16/8/1.
//  Copyright © 2016年 yuf. All rights reserved.
//

#import "StoneStreetStoreDetailViewController.h"
#import "StoreDetailCollectionViewCell.h"
#import "StoneStreetDetailViewController.h"
#import "CommitStarsView.h"

static NSString * cellIndentifier = @"StoreDetailCollectionViewCell";

@interface StoneStreetStoreDetailViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,BestScrollViewDelegate,BestScrollViewDatasource>{
    NSInteger _totle;
}
@property (nonatomic,assign)   NSInteger    pageNO;
@property (weak, nonatomic) IBOutlet UIScrollView *scroView;
@property (weak, nonatomic) IBOutlet UIButton *collectButton;
@property (weak, nonatomic) IBOutlet UILabel *storeName;
@property (weak, nonatomic) IBOutlet UITextView *textView;
@property (weak, nonatomic) IBOutlet UILabel *storeAddress;
@property (weak, nonatomic) IBOutlet UILabel *storePhone;
@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;
@property (nonatomic,strong)  BestScrollView *headerScroll;//滚动栏
@property (nonatomic,strong)  NSMutableArray  *imageArray;
@property (nonatomic,strong)  NSMutableArray  *goodsArray;
@property(nonatomic,strong)NSString * transPrice;
@end

@implementation StoneStreetStoreDetailViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    _pageNO = 1;
    _imageArray = [NSMutableArray array];
    _goodsArray = [NSMutableArray array];
    [self initViewLayout];
    [self getShopDetail];
    [self addRefreshing];
    // Do any additional setup after loading the view.
}

- (void)initViewLayout{
    [self adaptiveViewLayout:self.view];
    [self adaptiveViewLayout:self.scroView];
    
    _scroView.contentSize = flexibleSize(CGSizeMake(0, 780), NO);
    
    UICollectionViewFlowLayout *flowLayout =[[UICollectionViewFlowLayout alloc]init];
    flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
    flowLayout.minimumInteritemSpacing = 0;
    flowLayout.minimumLineSpacing = 0;
    self.collectionView.backgroundColor = [UIColor clearColor];
    self.collectionView.collectionViewLayout = flowLayout;
    [self.collectionView registerNib:[UINib nibWithNibName:cellIndentifier bundle:nil] forCellWithReuseIdentifier:cellIndentifier];
    self.collectionView.dataSource = self;
    self.collectionView.delegate = self;
    
    _headerScroll = [[BestScrollView alloc]  initWithFrame:flexibleFrame(CGRectMake(0, 0, 320, 185), NO)];
    [self.scroView insertSubview:_headerScroll belowSubview:_collectButton];
    
    
}

- (IBAction)back:(id)sender {
    [self backBtn];
}

#pragma mark == 收藏
- (IBAction)collectHandel:(UIButton *)sender {
   
        if (![Common getLoginStatus]) {
            [[AppDelegate sharedAppDelegate]ShowLoginPage];
            return ;
        }
        NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
        
        [dic setObject:[Common getLoginInfo][@"userId"] forKey:@"museId"];
        [dic setObject:[Common getLoginInfo][@"userId"] forKey:@"msadMemberId"];
        [dic setObject:[Common getLoginInfo][Key_User_password] forKey:@"musePwd"];
        [dic setObject:[Common getLoginInfo][Key_User_onlineKey] forKey:@"museOnlineTag"];
        [dic setObject:_storeId forKey:@"mstoId"];
        
        NSString * lan = [InternationalControl userLanguage];
        if ([lan isEqualToString:@"en"]) {
            [dic setObject:@"2" forKey:@"language"];
        }else{
            [dic setObject:@"1" forKey:@"language"];
        }
        
        self.shareApi.delegate=self;
       
    if (!sender.selected) {
     [self.shareApi  requestOperationWithDic:dic withPath:GS_mallCollectStore withHttpType:@"POST" withTag:GS_GS_mallCollectStore];
    }else{
     [self.shareApi  requestOperationWithDic:dic withPath:GS_canleMallCollectStore withHttpType:@"POST" withTag:GS_GS_canleMallCollectStore];
    }
}

#pragma mark == 地图
- (IBAction)navHandel:(id)sender {
}

#pragma mark == 呼叫
- (IBAction)callHandel:(id)sender {
}

#pragma mark === 获取商家详情
- (void)getShopDetail{
    if (![Common getLoginStatus]) {
        [[AppDelegate sharedAppDelegate]ShowLoginPage];
        return ;
    }
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    
    [dic setObject:[Common getLoginInfo][@"userId"] forKey:@"museId"];
    [dic setObject:[Common getLoginInfo][@"userId"] forKey:@"msadMemberId"];
    [dic setObject:[Common getLoginInfo][Key_User_password] forKey:@"musePwd"];
    [dic setObject:[Common getLoginInfo][Key_User_onlineKey] forKey:@"museOnlineTag"];
    [dic setObject:_storeId forKey:@"mstoId"];
    
    NSString * lan = [InternationalControl userLanguage];
    if ([lan isEqualToString:@"en"]) {
        [dic setObject:@"2" forKey:@"language"];
    }else{
        [dic setObject:@"1" forKey:@"language"];
    }
    
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:GS_queryMallStoreDetail withHttpType:@"POST" withTag:GS_GS_queryMallStoreDetail];
}

#pragma mark -- 添加刷新数据
- (void)addRefreshing{
    self.scroView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        int64_t delayInSeconds = 8.0;
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            [self.scroView.header endRefreshing];
        });
        self.pageNO = 1;
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            //请求订单数据
            [self getShopList];
        });
    }];
    [_scroView.header beginRefreshing];
}
//加载更多数据
- (void)loadMoreData{
    if (self.goodsArray.count == _totle) {
        [self.scroView.footer endRefreshing];
    }else{
        self.pageNO = self.pageNO + 1;
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            //请求订单数据
            [self getShopList];
        });
    }
    
}


#pragma mark === 获取商家商品列表
- (void)getShopList{
    if (![Common getLoginStatus]) {
        [[AppDelegate sharedAppDelegate]ShowLoginPage];
        return ;
    }
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    
    [dic setObject:[Common getLoginInfo][@"userId"] forKey:@"museId"];
    [dic setObject:[Common getLoginInfo][@"userId"] forKey:@"msadMemberId"];
    [dic setObject:[Common getLoginInfo][Key_User_password] forKey:@"musePwd"];
    [dic setObject:[Common getLoginInfo][Key_User_onlineKey] forKey:@"museOnlineTag"];
    [dic setObject:_storeId forKey:@"mstoId"];
    
    NSString * lan = [InternationalControl userLanguage];
    if ([lan isEqualToString:@"en"]) {
        [dic setObject:@"2" forKey:@"language"];
    }else{
        [dic setObject:@"1" forKey:@"language"];
    }
    
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:GS_queryMallGoodsList withHttpType:@"POST" withTag:GS_GS_queryMallGoodsList];
}


#pragma mark -- UICollectionViewDataSource
//定义展示的UICollectionViewCell的个数
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
        return _goodsArray.count;
}
//定义展示的Section的个数
-(NSInteger)nmumberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

//定义每个UICollectionView 的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake(158*VerticalRatio(), 138*VerticalRatio());
}
//定义每个UICollectionView 的 margin
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(0,0, 0, 0);
    
}
//每个UICollectionView展示的内容
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
        StoreDetailCollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellIndentifier forIndexPath:indexPath];
    NSDictionary * dic = _goodsArray[indexPath.row];
    cell.nameLabel.text = [NSString stringWithFormat:@"%@",dic[@"mgooName"]];
    cell.priceLabel.text = [NSString stringWithFormat:@"￥%@",dic[@"mgooPrice"]];
    cell.typeLabel.text = [NSString stringWithFormat:@"%@",dic[@"mgooSpecify"]];
    
    NSString * image = [NSString stringWithFormat:@"%@",dic[@"mgooImage"]];
    if (image.length>0) {
        [cell.storeImage sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",IP_Address_ImageDown_Fresh,image]]];
    }
    
    cell.putShopCarBolok = ^(){
    
    };
        return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    UIStoryboard * storyBoard = [UIStoryboard storyboardWithName:@"HomeStoryboard" bundle:nil];
    StoneStreetDetailViewController * page = [storyBoard instantiateViewControllerWithIdentifier:@"StoneStreetDetail"];
    page.stoneId = _goodsArray[indexPath.row][@"mgooId"];
    page.storeName = _storeName.text;
    page.storeId = _storeId;
    page.transPrice = _transPrice;
    [[Common getNavigation]pushViewController:page];
}

#pragma  mark BestView Delegate Data=source=====================


- (NSInteger)numberOfPages
{
    
    return  self.imageArray.count;
    
}

- (UIView *)pageAtIndex:(NSInteger)index
{
    
    if (self.imageArray.count>0) {
        
        UIImageView  *imageView=[[UIImageView alloc]  initWithFrame: flexibleFrame(CGRectMake(0, 0, 320, 185), NO)];
        [imageView  sd_setImageWithURL:[NSURL URLWithString: [NSString stringWithFormat:@"%@%@",IP_Address_ImageDown_Fresh,_imageArray[index][@"msimImage"]]] placeholderImage:[UIImage imageNamed:@"beijing"]];
        return imageView;
    }
    return nil;
}


- (void)didClickPage:(BestScrollView *)csView atIndex:(NSInteger)index
{
}



#pragma   mark---- GetADBanner Request Delegate

-(void)fetchDatabaseFinished:(NSMutableDictionary *)database withTag:(NSInteger)tag{
    [_scroView.header endRefreshing];
     [_scroView.footer endRefreshing];
    if (tag == GS_GS_queryMallStoreDetail){
        if (  [[database valueForKey:@"flag"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else  {
            
            NSDictionary * dic = database[@"result"];
            NSString * collect = [NSString stringWithFormat:@"%@",dic[@"isCollect"]];
            if ([collect isEqualToString:@"1"]) {
                _collectButton.selected = YES;
            }else{
                _collectButton.selected = NO;
            }
            
            dic = dic[@"store"];
            _transPrice = [NSString stringWithFormat:@"%@",dic[@"mstoFreight"]];
            _storeName.text = [NSString stringWithFormat:@"%@",dic[@"mstoName"]];
            _textView.text = [NSString stringWithFormat:@"%@",dic[@"mstoContent"]];
            _storePhone.text = [NSString stringWithFormat:@"%@",dic[@"mstoPhone"]];
            _storeAddress.text = [NSString stringWithFormat:@"%@",dic[@"mstoAddress"]];
            if(![dic[@"mstoCredit"] isEqual:[NSNull null]]){
                CGFloat starts = [dic[@"mstoCredit"]floatValue];
                CommitStarsView * startView = [[CommitStarsView alloc]initWithFrame:flexibleFrame(CGRectMake(80, 215, 70, 10), NO) SmallStars:starts];
                [_scroView addSubview:startView];
            }

            self.imageArray =database[@"result"][@"images"];
            if (_imageArray.count==0) {
                return;
            }
            self.headerScroll.delegate=self;
            self.headerScroll.datasource=self;
            [self.headerScroll showImageArray:self.imageArray   withAnimation:YES];
          
        }
    }else if (tag == GS_GS_mallCollectStore){
      
        if (  [[database valueForKey:@"flag"] integerValue]!=1 ) {
                
                [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
                
        }else  {
                [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            _collectButton.selected = YES;
        }
        
    }else if (tag == GS_GS_canleMallCollectStore){
        if (  [[database valueForKey:@"flag"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else  {
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            _collectButton.selected = NO;
        }

    }else if (tag == GS_GS_queryMallGoodsList){
        if (  [[database valueForKey:@"flag"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else  {
            dispatch_async(dispatch_get_main_queue(), ^{
                _totle = [database[@"result"][@"total"] integerValue];
                if (_totle > PageSize) {
                    __weak __typeof(self) weakSelf = self;
                    if (!self.scroView.footer) {
                        // 设置回调（一旦进入刷新状态就会调用这个refreshingBlock）
                        self.scroView.footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
                            [weakSelf loadMoreData];
                        }];
                    }
                }
                if (self.pageNO == 1) {
                    [self.goodsArray removeAllObjects];
                }
                NSArray *arr = database[@"result"][@"list"];
                for (id entity in arr) {
                    [self.goodsArray addObject:entity];
                }
                
                [_collectionView reloadData];
                
            });
            
        }
    }
}

-(void)fetchDatabaseFailed:(NSError *)error message:(NSString *)message{
    [_scroView.header endRefreshing];
    [_scroView.footer endRefreshing];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
